﻿using Light.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Light.Framework
{
    /// <summary>
    /// 排序对象
    /// </summary>
    public class ResultOrder
    {
        Dictionary<string, bool> dic = new Dictionary<string, bool>();

        /// <summary>
        /// 设置排序
        /// </summary>
        /// <param name="name">排序属性，值true表示升序，false表示降序</param>
        /// <returns></returns>
        public bool this[string name]
        {
            get
            {
                if (dic.Keys.Contains(name))
                    return dic[name];
                else
                    return false;
            }
            set
            {
                if (dic.Keys.Contains(name))
                    dic[name] = value;
                else
                    dic.Add(name, value);
            }
        }

        public void Add(string field, bool isAscending)
        {
            if (!dic.Keys.Contains(field))
                dic.Add(field, isAscending);
            else
                dic[field] = isAscending;
        }

        public void Clear()
        {
            dic.Clear();
        }

        /// <summary>
        /// 是否为空
        /// </summary>
        public bool IsEmpty
        {
            get
            {
                return dic.Count == 0;
            }
        }

        /// <summary>
        ///  转表或视图的排序列
        /// </summary>
        /// <returns></returns>
        public string ToSqlString()
        {
            StringBuilder builder = new StringBuilder();

            foreach (var columnName in dic.Keys)
            {
                builder.Append(columnName + " " + (dic[columnName] ? "ASC" : "DESC"));
                builder.Append(",");
            }
            if (dic.Count > 0)
            {
                builder.Remove(builder.Length - 1, 1);
            }
            return builder.ToString();
        }
    }
}
